# -*- coding: utf-8 -*-

import datetime,logging,time

from program_top.utilities.my_datetime import my_date_time_microsec_format

class my_logging_format(logging.Formatter):#我的日志时间格式，包含毫秒
	def formatTime(self, record, datefmt=None):

		ct=self.converter(record.created)
		if datefmt:
			s=time.strftime(datefmt,ct)
		else:
			s=str(datetime.datetime.now())
			pass
		return s
	pass

class my_logger(object):
	'''
	记录日志的实例
	'''
	def __init__(self,log_writting_instance):
		'''如果哪个类想要写入日志，可以把自己传入日志类的构造函数'''
		
		self.__logged_id=id(log_writting_instance)#被记录类实例的id
		self.__logged_class=log_writting_instance.__class__.__name__#被记录实例的类名称
		
		self.logger_name="%s,%d"%(self.__logged_class,self.__logged_id)#logger_name
		log_path=log_writting_instance._environment_pack['runtime_paths']['output_dir']
		self.__log_file_encoding=log_writting_instance._environment_pack['current_platform_info']['current_system_encoding']#读取当前运行操作系统的内码，输出日志文件时使用
		the_logger=logging.getLogger(self.logger_name)
		the_logger.setLevel(logging.CRITICAL)
		the_log_format=logging.Formatter()
		log_filename=log_path+self.logger_name+'.log'
		log_file=logging.FileHandler(log_filename)
		log_file.setLevel(logging.CRITICAL)
		log_file.setFormatter(the_log_format)
		the_logger.addHandler(log_file)
		log_print=logging.StreamHandler()
		log_print.setLevel(logging.CRITICAL)
		log_print.setFormatter(the_log_format)
		the_logger.addHandler(log_print)
		self.__the_logger=the_logger
		self.__logger_print=log_print
		self.__log_file=log_file
		pass
	
	def write_log(self, log_message):
		time_now=datetime.datetime.now().strftime(my_date_time_microsec_format)
		join_message=','.join([time_now,log_message].decode('utf-8').encode(self.__log_file_encoding))
		self.__the_logger.critical(join_message)
		pass
	pass

